<template>
  <div class="patient" v-loading="loading">
    
    <div class="patient-main-info" style="position: relative;">
        <div class="eidt-btn">
          <el-button class="btn-1" v-if="!isEdit" @click="onEdit" v-jurisdiction="'customer:info:update'">修改</el-button>
          <el-button class="btn-2" v-if="isEdit" @click="cancel">取消</el-button>
          <el-button class="btn-1" v-if="isEdit" @click="save">保存</el-button>
    
        </div>
          <ztitleBorderBottom title="个人信息">
              <template v-if="isEdit">
                  <component :is="showWidget(item.type)"  v-for="item in infoAdd" :key="item.name" :struc="item" :passWidth="33.33" />
              </template>
              <template v-else>
                  <div class="person-detail-info">
                    <div class="details-left-basic">
                      <div class="basic-info-item" v-for="i in personDetail" :key="i.name">
                        <div class="lable">{{i.viewName}}:</div>
                        <div class="info">{{i.value}}</div>
                      </div>
                      <!-- 推荐人数 -->
                      <div class="basic-info-item" style="width: 100%;">
                        <div class="lable">推荐人数:</div>
                        <div class="info">
                          <span>{{customerCount}} 人</span>
                          <el-tooltip
                            class="item"
                            effect="dark"
                            content="查看被推荐人"
                            placement="top"
                          > 
                          <el-icon @click="showViewReferrals"><View /></el-icon>
                          </el-tooltip>
                          
                        </div>
                      </div>
                      
                    </div>
                    <div class="details-avarat-img">
                      <el-image
                          class="image-position"
                          style="width: 100px; height: 100px"
                          :src="avaratImg"
                          fit="cover">
                          <template #error>
                              <div class="image-slot">
                                <el-icon><Picture /></el-icon>
                              </div>
                            </template>
                          </el-image>
                    </div>
                  </div>
                  <!-- 亲友关系 -->
                  <relationship :self="self"></relationship>
              </template>
              
              
          </ztitleBorderBottom>
    </div>

      <!-- 查看推荐人 -->
      <zdialog @handleClose="close" v-model="dialogVisible" :btnData="btnData" title="查看被推荐人">
        <template #body>
          <ztable 
            :tableData='refreshdata' 
            :strucs='seeRefreshColumn'
            :height="'100%'"
          ></ztable>
        </template>
      </zdialog>

    <!-- <div class="" v-if="false">
          <ztitleBorderBottom title="客户关系">
              
              <template v-if="isEdit">
                  <component :is="showWidget(item.type)"  v-for="item in resultAdd" :key="item.name" :struc="item"  />
              </template>
              <template v-else>
                <el-descriptions :column="4" border style="width: 100%">
                  <el-descriptions-item
                    v-for="item in resultAdd" :key="item.name"
                    :label="item.viewName"
                    label-align="right"
                    align="center"
                    label-class-name="my-label"
                    class-name="my-content"
                    >
                    <el-tag size="small">{{ item.value && UserObj[item.value]}}</el-tag>
                    </el-descriptions-item
                  >
                </el-descriptions>
              </template>
              
          </ztitleBorderBottom>
      </div> -->
    <!-- <div class="dynamic f-w">
        <ztitleBorderBottom title="客户初诊">
            <component :is="showWidget(item.type)"  v-for="item in DiagnosisAdd" :key="item.name" :struc="item" :passWidth="25" />
        </ztitleBorderBottom>
    </div> -->
    
  </div>
</template>

<script lang="ts">
import { View, Picture } from '@element-plus/icons-vue'
import { defineComponent, reactive, toRefs, ref, watch, computed, onMounted } from "@vue/runtime-core";

import useShowWidget from "../../../components/widget/usechoose";
import useConfgin from '../../../hook/getconfig'
import useRequet, { RespData } from "../../../hook/network"
import { ElMessage } from 'element-plus'

import zdialog from '@components/dialog/dialog.vue'
import ztable from '@components/Table/index.vue'
import relationship from './components/relationship.vue'
import ztitleBorderBottom from "../../../components/titleBorder/titleBorderBottom.vue";
import { getBirthDay } from "../../../usefn/getBirthday"
import { useRoute } from 'vue-router'


const ID = 518 // 患者中心
const RELATION = 519 // 患者关系
const INITIALDIAGNOSIS = 520 // 客户初诊
export default defineComponent({
  name: 'Patient',
  components:{
      ztitleBorderBottom,
      zdialog,
      ztable,
      relationship,

      View, Picture
  },
  emits: ['refreshInfo'],
  setup(props, ctx) {
    const route = useRoute()
    const request = useRequet({ path: "" });
    let id = route.params.id;

    const infoTotal = useConfgin(ID)
		const infoAdd = infoTotal.groupDataAdd
    const resultTotal = useConfgin(RELATION)
		const resultAdd = resultTotal.groupDataAdd

    watch(() => route.params.id, (newID, prevID) => {
      id = newID
      if(newID) {
        getPersonInfo()
        getRefreshData()
      }
      
    })
    
    onMounted(() => {
      if(id) {
        getPersonInfo()
        getRefreshData()
      }
      getUserList()
      getCustomerTypeList()
      
    })
		// const InitialDiagnosis = useConfgin(INITIALDIAGNOSIS)
		// const DiagnosisAdd = InitialDiagnosis.groupDataAdd
    const loading = ref(false)
    // 患者详情展示
    let avaratImg:any = ref('')
    let personDetail = computed(() => {
      let obj:any = []
      infoAdd.value.forEach((item,index) => {
        if(item.name === "avatarUrl"){
          avaratImg.value = item.value
          return false
        }

        obj.push({
          viewName: item.viewName,
          value: item.value
        })
      })

      obj.forEach((i: any) => {
          if(i.viewName === '患者类型'){
            i.value = TypeObj.value[i.value]
          }
          if(i.viewName === '患者来源') {
            i.value = personInfo.value.scoreShow
          }
          if(i.viewName === '电话') {
            i.value = personInfo.value.phoneNumStr
          }
          if(i.viewName === '手机') {
            i.value = personInfo.value.mobileNumStr
          }
          if(i.viewName === '生日') {
            i.value = getBirthDay(i.value)
          }
        })

      return obj
    })

    const save = () => {
      let obj = {} as any
      obj.id = id
      infoAdd.value.forEach(item => {
        obj[item.name] = item.value
        if(item.name == 'birthDate') {
          obj[item.name] = item.value + ' ' + '00:00:00'
        }
        
      })
      loading.value = true
      
      request.sendRequest({
        address: 'customer/info/updateCustomerInfo',
        params: obj,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
					ElMessage.success('修改'+ resp.msg)
          isEdit.value = false
          loading.value = false
          getPersonInfo()
          // 暴露出去刷新
          ctx.emit('refreshInfo')
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })

      isEdit.value = true
    }

    const cancel = () => {
      isEdit.value = false
    }
    const isEdit = ref(false)
    const onEdit = () => {
      isEdit.value = true
    }
    type TypeObj = {
      id: string,
      name: string
    }
    const TypeObj = ref({} as any)
    // 得到患者类型
    const getCustomerTypeList = () => {
      request.sendRequest({
        address: 'customer/info/getCustomerTypeList',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
            resp.data.forEach((item: any) => {
              TypeObj.value[item.id] = item.name 
            })
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    
    const UserObj = ref({} as any)
    // 得到责任医生/ 咨询师
    const getUserList = () => {
      request.sendRequest({
        address: 'warehouse/inOrder/getUserList',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
            resp.data.forEach((item: any) => {
              UserObj.value[item.id] = item.name 
            })
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })


    }
    
    type SelfType = {
      name: string,
      gender: string
    }
    const self = ref(<SelfType>{})
    const personInfo = ref<any>({})
    // 得到患者信息
    const getPersonInfo = () => {
      loading.value = true
      request.sendRequest({
        address: `customer/info/getCustomerInfoDetail/${id}`,
        params: {
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg )
          personInfo.value = resp.data.customerInfo
          let customerInfo = resp.data.customerInfo
          let other = customerInfo.other
          let deptConfig = resp.data.deptConfig || []

          self.value.name =  customerInfo.name
          self.value.gender =  customerInfo.gender

          customerCount.value  = customerInfo.recommendedCustomerCount
          
          Object.keys(customerInfo).forEach(i => {
            
            
              infoAdd.value.forEach(item => {
                
                if(item.name === 'other.firstSource') {
                  item.value = other.firstSource
                }
                if(item.name === 'other.secondSource') {
                  item.value = other.secondSource
                }
                if(item.name === 'other.thirdSource') {
                  item.value = other.thirdSource
                }
                if(item.name === i) {
                  item.value = customerInfo[i]
                }

            })
          })
            // customerInfo[item.name] = customerInfo[item.name]
          Object.keys(deptConfig).forEach(i => {
            resultAdd.value.forEach(item => {
              if(item.name === i) {
                item.value = deptConfig[i]
              }
            })
          })

          loading.value = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          loading.value = false
        },
        method: "GET",
      })

      // loading.value = false
    }

    const dialogVisible = ref(false)
    const close = () => {
      dialogVisible.value = false
    }
    const seeRefreshColumn = ref([
        {
          id: 529,
            name: "name",
            viewName: "姓名",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "mobileFirstNumStr",
            viewName: "手机",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "gender",
            viewName: "性别",
            type: 202,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "cityName",
            viewName: "地址",
            type: 202,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        }
    ])
    const customerCount = ref(0)
    const refreshdata = ref([])
    const getRefreshData = () => {
      request.sendRequest({
        address: `customer/info/getRecommendedCustomerList/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
            refreshdata.value = resp.data
            console.log(refreshdata.value)
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    
    // 推荐人查看
    const showViewReferrals = () => {
      dialogVisible.value = true
    }

    const btnData = [
      {
        name: '关闭',
				func: (data:object) => {
          close()
				}
      },
    ]
    
    const showWidget = useShowWidget;

    return {
      infoAdd,
      resultAdd,
      isEdit,
      // DiagnosisAdd,
      loading,
      TypeObj,
      UserObj,
      personDetail,
      avaratImg,

      showWidget,
      request,
      getPersonInfo,
      getUserList,
      getCustomerTypeList,
      refreshdata,
      seeRefreshColumn,
      customerCount,
      self,

      showViewReferrals,
      dialogVisible,
      close,
      btnData,

      save,
      cancel,
      onEdit

    }
  }
})
</script>

<style scoped lang="scss">
.patient {
  padding: 15px;
  overflow-y: auto;
  height: 100%;
  box-sizing: border-box;

  .patient-main-info {
    // height: calc(100% + 40px);
  }
  .patient-footer {
    text-align: right;
  }
}

.eidt-btn {
  position: absolute;
  right: 10px;
  z-index: 9;
}

.person-detail-info {
  display: flex;
  width: 100%;
  box-shadow: 0 2px 8px #e9e9e9;
  border-radius: 8px;
  background: white;

  .details-left-basic {
    width: calc(100% - 150px);
    height: 100%;
    // background: red;
    padding: 15px;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;

    .basic-info-item {
      display: flex;
      margin: 10px 15px;
      color: $primaryText;
      font-size: 14px;
      line-height: 35px;
      min-width: 33.33%;
      box-sizing: border-box;

      .lable {
        padding-right: 10px;
        width: 80px;
      }

      .info {
        span {
          padding-right: 10px;
        }
        & > i {
          cursor: pointer;
          font-weight: 500;
          font-size: 18px;
          color: #ff6662;
        }
        // width: calc(100% - 80px);
      }
    }
  }

  .details-avarat-img {
    // background: yellow;
    width: 150px;
    display: flex;
    justify-content: center;
    padding-top: 20px;
  }
}
</style>